package utils

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/pem"
	"errors"
)

var privateKey = []byte(`
-----BEGIN RSA PRIVATE KEY-----
MIIJKQIBAAKCAgEA4COIbr4LIY48LAztjVoMsjP9hx0Ug0ckRI0ltAQhlGEWODvM
wHsyNIW732w9egLW0HkRWdG95fgiA6JwGr0aPV5fIFgBKWT61JnVmdj3ujd8YC4+
j7jvqmuZspUqq2PlMT55y/nrGIzVosaXeRWKfbGRS1TVKoZQ+buuONtSFDX5aTco
tBw5NOuS12ol5Mvp2ZzNfIxUMmnsK6G0Y6VA0podoVcEs3hWzJVOm7yVysqGEb1r
kSw9bu4kcLZomPHRwC0AiyOoQblXbQQ+2lGhuzrY6HlqRLHq6QDi8GEJ4aG4PMlU
fQ/JozHgshqjCIxvIzdlKJvM9Qo2DpiigGDSKrIC4b5p7WOQcj4qCmsrdARyWiOD
mqlGsP+07hz4fotD1pH+e9TEuWacPX7plqHU8LRQ4+bcucVxhYVRT9Sk+6fWbsDA
Jn3rVP6fDfG8e+Jw1QvcstaSNm0iQqNUCxLHX6cbRi+xgHnCVhd4A1EQ+XosX9Ab
3VVD87p6ia/0CQKjnWKO685wQgnO6ncdr+us5XX69VluKXUEQM1a9HRv/COW4cqC
Br0jaI1xOaUwhC61P5jxVmRVdOliBwE0TtgfJbQ8FrD3EFGcb3/T0px1Ox++ymo0
6t5vMmDMZr88e4oLVejd2CmNuwyeUY1qbQZ+cfwLvjGV0lEu0puYY9FRyuMCAwEA
AQKCAgEAsFgEfWyUAWCQwu+g7rdMieARtf4RJ4APbsfGRC2D5ePEwZV68G19AIm/
WHcmnxogvICkQBCe4ZIp4MYqgT8KqAHZwe67a0ABgMdPoO1taltBRcLcgeM03NYv
ZKurmJDNv8KxvOPyLayQYLLyddeW0HGmKKij1gM7LmCVIDKeDzyv8DHvmlUiRRqa
u1TOX4Z3hDi0Cyu1Crz/jQx6inN33rpWWZvHHRSu5eMKp8jl6VkRxl9LhDpUUzSW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ZlQSbueEg
9P2OTtaTV8yjCZqWt86CCYa8m1YRIeLGRfYGa25BCcxfVQqA0jUjZtn4huEW
-----END RSA PRIVATE KEY-----
`)

var publicKey = []byte(`
-----BEGIN PUBLIC KEY-----
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA4COIbr4LIY48LAztjVoM
sjP9hx0Ug0ckRI0ltAQhlGEWODvMwHsyNIW732w9egLW0HkRWdG95fgiA6JwGr0a
PV5fIFgBKWT61JnVmdj3ujd8YC4+j7jvqmuZspUqq2PlMT55y/nrGIzVosaXeRWK
fbGRS1TVKoZQ+buuONtSFDX5aTcotBw5NOuS12ol5Mvp2ZzNfIxUMmnsK6G0Y6VA
0podoVcEs3hWzJVOm7yVysqGEb1rkSw9bu4kcLZomPHRwC0AiyOoQblXbQQ+2lGh
uzrY6HlqRLHq6QDi8GEJ4aG4PMlUfQ/JozHgshqjCIxvIzdlKJvM9Qo2DpiigGDS
KrIC4b5p7WOQcj4qCmsrdARyWiODmqlGsP+07hz4fotD1pH+e9TEuWacPX7plqHU
8LRQ4+bcucVxhYVRT9Sk+6fWbsDAJn3rVP6fDfG8e+Jw1QvcstaSNm0iQqNUCxLH
X6cbRi+xgHnCVhd4A1EQ+XosX9Ab3VVD87p6ia/0CQKjnWKO685wQgnO6ncdr+us
5XX69VluKXUEQM1a9HRv/COW4cqCBr0jaI1xOaUwhC61P5jxVmRVdOliBwE0Ttgf
JbQ8FrD3EFGcb3/T0px1Ox++ymo06t5vMmDMZr88e4oLVejd2CmNuwyeUY1qbQZ+
cfwLvjGV0lEu0puYY9FRyuMCAwEAAQ==
-----END PUBLIC KEY-----
`)

// 解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {

	block, _ := pem.Decode(privateKey)
	if block == nil {
		return nil, errors.New("private key error!")
	}
	priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
		return nil, err
	}

	return rsa.DecryptPKCS1v15(rand.Reader, priv, ciphertext)
}

// 加密
func RsaEncrypt(origData []byte) ([]byte, error) {
	block, _ := pem.Decode(publicKey)
	if block == nil {
		return nil, errors.New("public key error")
	}

	pubInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
	if err != nil {
		return nil, err
	}
	pub := pubInterface.(*rsa.PublicKey)
	return rsa.EncryptPKCS1v15(rand.Reader, pub, origData)
}
